package com.suntop.carousel.qlmediaplay.danmu;

import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.text.style.ReplacementSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class LinearGradientFontSpan extends ReplacementSpan {
    private float mSize;
    private int startColor;
    private int centerColor;
    private int endColor;

    public LinearGradientFontSpan(int startColor, int centerColor, int endColor) {
        this.startColor = startColor;
        this.centerColor = centerColor;
        this.endColor = endColor;
    }

    public LinearGradientFontSpan(int startColor, int endColor) {
        this.startColor = startColor;
        this.endColor = endColor;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        mSize  = paint.measureText(text, start, end);
        Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
        if (fm!=null){
            fm.ascent=fontMetricsInt.ascent;
            fm.top=fontMetricsInt.top;
            fm.bottom=fontMetricsInt.bottom;
            fm.descent=fontMetricsInt.descent;
        }

        return (int) mSize;
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        LinearGradient  linearGradient=new LinearGradient(0,top,0,bottom
        ,centerColor!=0?new int[]{startColor,centerColor,endColor}:new int[]{startColor,endColor}
        ,centerColor!=0?new float[]{0,0.5f,1.0f}:new float[]{0.5f,1.0f}, Shader.TileMode.REPEAT);
        paint.setShader(linearGradient);
        paint.setFakeBoldText(true);
        canvas.drawText(text,start,end,x,y,paint);
    }
}
